// pages/seckill/seckill.js
const seckillService = require('../../../../api/seckillService.js')
const productService = require('../../../../api/productService.js')
const bannerService = require('../../../../api/bannerService.js')
const util = require('../../../../utils/utils.js')

const app = getApp()


Page({

  /**
   * 页面的初始数据
   */
  data: {
    timeList: [],
    goodsList: [],
    tabSelected: 0,
    time: {
      hour: '',
      minute: '',
      second: '',
    },
    secKillStatus: 'started', //started 开始 end 结束  ahead 即将开始
    secKillTips: '',
    banners: [],
    secKillTimeId: 0,
    phone: false
  },

  // 跳转到商品详情页面
  toGoodsDetail: function (val) {
    const that = this
    if (this.data.secKillStatus === 'started') {
      if (val.currentTarget.dataset.balance === 0) {
        if (val.currentTarget.dataset.goodsnum === 0) {
          wx.showToast({
            title: '您来晚了，已经被抢光了',
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '门店正在努力补货中,去其他门店看看吧~',
            success: function (res) {
              if (res.confirm) {
                wx.switchTab({
                  url: '../index/index'
                })
              } else if (res.cancel) {

              }
            }
          })
        }
      } else {
        if (val.currentTarget.dataset.goodsnum === 0) {
          wx.showToast({
            title: '您来晚了，已经被抢光了',
            icon: 'none',
            duration: 2000
          })
        } else {
          let goodsList = JSON.stringify(that.data.goodsList)
          let goodsId = val.currentTarget.dataset.goodsid
          let storeId = val.currentTarget.dataset.storeid
          let activityId = val.currentTarget.dataset.activityid
          productService.getDetails(storeId, goodsId).then(res => {
            console.log(res)
            if (res && res.balance > 0) {
              let url = '../../goods/goodsDetail/goodsDetail?productId=' + goodsId + '&storeId=' + storeId + '&type=secondkill&activityId=' + activityId
              if (that.options.mobile) {
                url = url + '&mobile=' + that.options.mobile
              }
              wx.navigateTo({
                url: url
              })
            } else {
              const i = that.data.tabSelected
              let tempList = that.data.timeList[i]
              tempList.products.forEach((item, index) => {
                if (item.productId === goodsId) {
                  that.data.timeList[i].products[index].balance = 0
                }
              })
              wx.showModal({
                title: '提示',
                content: '门店正在努力补货中,去其他门店看看吧~',
                success: function (res) {
                  if (res.confirm) {
                    wx.switchTab({
                      url: '../../index/index/index'
                    })
                  } else if (res.cancel) {

                  }
                }
              })
            }
          })
        }
      }
    } else {
      let data = new Date().getTime()
      let index = that.data.tabSelected
      let startTime = that.data.timeList[index].newStartTime
      if (startTime - data > 0) {
        wx.showToast({
          title: '还没有开始喔~',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '本场已经结束啦~',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },
  // 类目点击事件
  clickCategory: function (e) {
    this.setData({
      tabSelected: e.currentTarget.dataset.idx
    })
    const i = e.currentTarget.dataset.idx
    const timeList = this.data.timeList
    this.setData({
      secKillStatus: timeList[i].secKillStatus,
      secKillTips: timeList[i].secKillTips,
      time: {
        hour: timeList[i].countDownTime.hou,
        minute: timeList[i].countDownTime.min,
        second: timeList[i].countDownTime.sec,
      }
    })
  },
  getSecKillList: function (storeId) {
    const that = this
    console.log(storeId)
    let postData = {
      page: 1,
      pageSize: 100,
      stateIn: 'STARTED',
      storeIdEquals: storeId
    }
    seckillService.query(postData).then(res => {
      console.log(res)
      let tempSecKillList = []
      let tempTimeList = []
      if (res.records.length > 0) {
        res.records.forEach(item => {
          let time = item.startTime.split(' ');
          let hour = time.slice(0, 2)
          let data = new Date().getTime()
          let newStartTime = new Date(item.startTime.replace(/-/g, '/')).getTime()
          let newEndTime = new Date(item.endTime.replace(/-/g, '/')).getTime()
          let date = new Date()
          let tempDate = util.formatTime(date)
          let datetTime = tempDate.split(' ');
          let startDate = datetTime[0] + ' 00:00:00'
          let newStartDate = startDate.replace(/\//g, '-')
          let newstartDateStamp = new Date(startDate).getTime()
          let countDown = data - newStartTime
          let duration = (newEndTime - newStartTime) / 1000
          let durationStart = (newStartTime - newstartDateStamp) / 1000
          let tempTimeData = {
            id: item.id,
            name: item.name,
            startTime: item.startTime,
            endTime: item.endTime,
            time: time[1].slice(0, 5),
            duration: duration,
            countDown: countDown,
            newStartTime: newStartTime,
            newEndTime: newEndTime,
            products: [],
            storeId: item.storeId,
            secKillStatus: 'started',
            secKillTips: '',
            durationStart: durationStart,
            startDate: newStartDate
          }
          item.products.forEach((ele, index) => {
            let tempProducts = {
              activityId: ele.activityId,
              availableStockAmount: ele.availableStockAmount ? ele.availableStockAmount : 0,
              balance: ele.availableStockAmount ? ele.availableStockAmount : 0,
              imageUrl: ele.imageUrl,
              limitCount: ele.limitCount,
              originalPrice: ele.originalPrice,
              price: ele.price,
              productDescription: ele.productDescription ? ele.productDescription : '',
              productId: ele.productId,
              productName: ele.productName,
              storeId: ele.storeId,
              totalStockAmount: ele.totalStockAmount ? ele.totalStockAmount : 1,
            }
            if (ele.availableStockAmount < 0) {
              tempProducts = {
                ...tempProducts,
                availableStockAmount: 0
              }
            }
            let specifications = []
            let produtlabel = []
            let promotions = []
            if (ele.labels && ele.labels.length > 0) {
              ele.labels.forEach(item => {
                if (item.type === 'GOODSLABEL') {
                  produtlabel.push(item)
                } else if (item.type === 'PROMOTIONLABEL') {
                  promotions.push(item)
                }
              })
            }
            if (ele.propertys && ele.propertys.length > 0) {
              for (let i = 0; i < ele.propertys.length; i++) {
                const temp = ele.propertys[i];
                if (temp.propertyName === '规格') {
                  specifications = temp.propertyValue
                  break
                }
              }
            }
            let goodsId = ele.productId
            let storeId = ele.storeId
            // productService.getDetails(storeId, goodsId).then(res => {
            //   tempTimeData.products[index].balance = res.balance
            // })
            tempProducts = {
              ...tempProducts,
              produtlabel: produtlabel,
              specifications: specifications,
              promotions: promotions,
            }
            tempTimeData.products.push(tempProducts)
          })
          if (newStartTime > data) {
            tempTimeData = {
              ...tempTimeData,
              status: '未开始',
              active: false,
              secKillStatus: 'ahead',
              secKillTips: '本场尚未开抢'
            }
          } else if (data >= newEndTime) {
            tempTimeData = {
              ...tempTimeData,
              status: '已结束',
              active: false,
              secKillStatus: 'end',
              secKillTips: '本场已结束 快去赶下一场吧！'
            }
          } else(
            tempTimeData = {
              ...tempTimeData,
              status: '抢购中',
              active: false,
              secKillTips: '火热抢购ing'
            }
          )
          tempSecKillList.push(tempTimeData)
        });

        function compare(property) {
          return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            return value1 - value2;
          }
        }
        tempSecKillList.sort(compare('newStartTime')); //排序，从小到大
        let key = 0;
        let tempDuration = Number.POSITIVE_INFINITY;
        for (let i = 0; i < tempSecKillList.length; i++) {
          if (i === 0 && tempSecKillList[i].countDown >= 0) {
            tempDuration = tempSecKillList[i].countDown
          } else {
            if (tempSecKillList[i].countDown >= 0 && tempDuration > tempSecKillList[i].countDown && tempSecKillList[i].secKillStatus === 'started') {
              tempDuration = tempSecKillList[i].countDown
              key = i
            }
          }
        }
        /**
         * 秒杀活动的几种非常规状况
         * 1、当前时间内没有进行中的
         * 2、全部结束
         * 3、没有开始的
         * 1、3为一种情况，全部结束暂不处理？
         */
        tempSecKillList.forEach((item, index) => {
          if (index === key) {
            if (item.secKillStatus === 'started') {
              item = {
                ...item,
                status: '抢购中',
                active: true,
                secKillTips: '活动火热进行中！'
              }
              tempSecKillList[index] = item
            } else {
              let count = key + 1
              if (tempSecKillList[key].secKillStatus === 'ahead') {
                key = key
              } else if (tempSecKillList[key].secKillStatus === 'end') {
                if (tempSecKillList[count] !== undefined && tempSecKillList[count].secKillStatus === 'ahead') {
                  key = count
                }
              }
            }
          }
        });
        console.log(key)
        that.setData({
          timeList: tempSecKillList,
          goodsList: tempSecKillList[key].products,
          tabSelected: key,
          secKillTips: tempSecKillList[key].secKillTips,
          secKillStatus: tempSecKillList[key].secKillStatus,
        })
        /**
         * 计算倒计时的逻辑
         * 通过当前时间进行判断，
         * 如果活动开始则传入结束时间计算距离结束的时间
         * 如果活动未开始则传入开始时间计算距离开始的时间
         * 通过重复执行的倒计时函数一直对这些数据进行计算
         * 计算的耗时，待观察？
         */
        console.log(tempSecKillList)
        countDown()
        // 执行倒计时函数
        function countDown() {
          clearTimeout(that.data.secKillTimeId)
          let now = new Date()
          let nowTimeStamp = new Date(util.formatTime(now)).getTime()
          // 获取倒计时
          let timeInfo = [];
          // 将活动的结束时间参数提成一个单独的数组，方便操作
          tempSecKillList.forEach(o => {
            if (nowTimeStamp < o.newStartTime) {
              // 即将开始
              let tempTime = {
                openTeamTime: o.startDate,
                duration: o.durationStart
              }
              timeInfo.push(tempTime)
            } else if (nowTimeStamp > o.newEndTime) {
              // 已结束
              let tempTime = {
                openTeamTime: o.startTime,
                duration: o.duration
              }
              timeInfo.push(tempTime)
            } else if (nowTimeStamp >= o.newStartTime && nowTimeStamp < o.newEndTime) {
              // 进行中
              let tempTime = {
                openTeamTime: o.startTime,
                duration: o.duration
              }
              timeInfo.push(tempTime)
            }
          })
          let countDownArr = util.countDown(timeInfo)
          let count = 0
          let tabSelected = that.data.tabSelected
          countDownArr.forEach(time => {
            that.data.timeList[count].countDownTime = time
            count++
          })
          that.setData({
            timeList: that.data.timeList
          })
          that.setData({
            time: {
              hour: that.data.timeList[tabSelected].countDownTime.hou,
              minute: that.data.timeList[tabSelected].countDownTime.min,
              second: that.data.timeList[tabSelected].countDownTime.sec,
            }
          })
          let time = setTimeout(
            function () {
              countDown();
            }, 1000)
          that.setData({
            secKillTimeId: time
          })
        }
        console.log(that.data.timeList)
      } else {}
    })
  },
  
  // banner跳转
  bannerJumping: function (e) {
    const that = this
    let bannerId = e.currentTarget.dataset.id
    const bannerList = that.data.banners
    let advertisementInfo = null
    bannerList.forEach(item => {
      if (item.id === bannerId) {
        advertisementInfo = item
      }
    });
    console.log(advertisementInfo)
    that.toAdPage(advertisementInfo, 'banner')
  },

  // 前往广告页
  toAdPage: function (pageInfo, pageType) {
    const that = this
    if (pageInfo.linkType === 'APP') {
      // 应用
      // 判断跳转模块
      if (pageInfo.appReturnType === 'MIAOSHA') {
        wx.navigateTo({
          url: '../../activity/seckill/seckill'
        })
      } else if (pageInfo.appReturnType === "RECHARGE") {
        wx.navigateTo({
          url: '../../myCard/recharge/recharge'
        })
      } else if (pageInfo.appReturnType === "MEAL") {
        //  餐饮
      } else if (pageInfo.appReturnType === "RECEIVECOUPON") {
        // 领券中心
        wx.navigateTo({
          url: '../../coupon/couponCenter/couponCenter'
        })
      } else if (pageInfo.appReturnType === "ADVANCE_SELL_PRODUCT") {
        // 预售商品
        wx.navigateTo({
          url: '../../activity/advanceSell/advanceSell'
        })
      } else if (pageInfo.appReturnType === "TEAM_BUYING") {
        // 团购
        wx.navigateTo({
          url: '../../fightGroup/fightGroup/fightGroup'
        })
      } else if (pageInfo.appReturnType === "SCOREMALL") {
        // 积分商场
        wx.navigateTo({
          url: '../../score/scoreMall/scoreMall'
        })
      } else if (pageInfo.appReturnType === "INVITE_MEMBER") {
        // 邀请好友
        wx.navigateTo({
          url: '../../invite/invite'
        })
      } else if (pageInfo.appReturnType === "MEMBER_CARD") {
        // 会员卡
        wx.navigateTo({
          url: '../../myCard/memberCard/memberCard'
        })
      } else if (pageInfo.appReturnType === "MY_COUPON") {
        // 我的优惠券
        wx.navigateTo({
          url: '../../coupon/myCoupon/myCoupon'
        })
      } else if (pageInfo.appReturnType === "NEWMBR") {
        // 新用户专享
        wx.navigateTo({
          url: '../../activity/newmbrActivity/newmbrActivity'
        })
      }
    } else if (pageInfo.linkType === 'GRADPRODUCT') {
      // 秒杀商品
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.productId + '&storeId=' + app.globalData.storeInfo.id + '&type=secondkill'
      })
    } else if (pageInfo.linkType === 'PRODUCT') {
      // 商品 
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.productId + '&storeId=' + app.globalData.storeInfo.id + '&type=normal'
      })
    } else if (pageInfo.linkType === 'TEAMPRODUCT') {
      // 拼团商品 
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.teamActivityId + '&storeId=' + app.globalData.storeInfo.id + '&type=group'
      })
    } else if (pageInfo.linkType === 'COUPONACTIVITYDETAILS') {
      if (app.globalData.userInfo) {
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../coupon/couponDetails/couponDetails?couponActivityId=' + pageInfo.couponActivityId + '&type=assign&isExternal=false'
          })
        } else {
          wx.showToast({
            title: '您还不是会员，请绑定手机号成为会员~',
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            that.handlePopupPhone()
          }, 2000);
        }
      }
    } else if (pageInfo.linkType === 'URL') {
      // 链接
      let url = null
      if (pageType === 'activity') {
        url = pageInfo.linkUrl
      } else if (pageType === 'banner') {
        url = pageInfo.link
      }
      var index = '?'
      let webUrl = url
      if (url.indexOf(index) > -1) {
        webUrl = webUrl + '&storeId=' + this.data.storeId + '&type=normal'
      }
      let urlData = {
        url: encodeURIComponent(webUrl)
      }
      console.log(webUrl, urlData)
      let jsonUrl = JSON.stringify(urlData)
      wx.navigateTo({
        url: '../../advertising/advertising?webUrl=' + jsonUrl
      })
    } else {

    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.getMemberUserInfo()
    const self = this
    // 判断globalData.storeInfo有没有数据，有数据，则使用选择的门店数据，没有，则根据当前地理位置获取最近门店
    if (app.globalData.storeInfo) {
      self.setData({
        storeId: app.globalData.storeInfo.id,
      })
      console.log("123")
      this.getSecKillList(app.globalData.storeInfo.id)
      this.getBannerList(app.globalData.storeInfo.id)
    } else {
      // 获取当前地理位置，然后筛选出最近的门店，根据当前门店获取门店的商品
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude
          var longitude = res.longitude
          var speed = res.speed
          var accuracy = res.accuracy
          try {
            var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
            if (tempAllStores) {
              // Do something with return value
              let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
              app.globalData.storeInfo = tempAllStores[tempIndex];
              // 获取当前门店的所有分类和商品
              self.getSecKillList(tempAllStores[tempIndex].id)
              self.getBannerList(tempAllStores[tempIndex].id)
            } else {
              // 查询所有门店
              storeService.queryList().then(res => {
                var allStores = res;
                try {
                  wx.setStorageSync('wj_allStores', allStores)
                } catch (e) {
                  console.log(e)
                }
                let tempIndex = self.getNearestStore(allStores, latitude, longitude);
                return allStores[tempIndex]
              }).then(res => {
                app.globalData.storeInfo = res;
                self.getSecKillList(res.id)
                self.getBannerList(res.id)
              })
            }
          } catch (e) {
            // Do something when catch error
          }
        }
      })
    }
    if (options.scene) {
      var scene = decodeURIComponent(options.scene)
      wx.showToast({
        title: scene,
        icon: 'none',
        duration: 2000
      })
      try {
        wx.setStorageSync('wj_sharingId', scene)
      } catch (e) {}
    }
    if (self.options.mobile && self.options.mobile != '' && self.options.mobile != undefined) {
      const mobile = self.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let storeId = ''
    if (app.globalData.storeInfo) {
      storeId = app.globalData.storeInfo.id
      this.setData({
        storeId: app.globalData.storeInfo.id
      })
      this.getSecKillList(storeId)
    }
    if (this.data.phone === true) {
      this.handlePopupPhone()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.data.secKillTimeId)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/activity/seckill/seckill?mobile=' + memberId,
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {}
      }
    } else {
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/activity/seckill/seckill',
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {}
      }
    }
  },
  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      store: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },
  // 前往首页
  toHome: function () {
    wx.switchTab({
      url: '../index/index'
    })
  },
  // 获取缓存的用户信息
  getMemberUserInfo: function () {
    if (!app.globalData.userInfo) {
      wx.showToast({
        title: "您还未授权，请登陆授权",
        icon: 'none',
        duration: 2000
      })
    } else {

    }
  },
  /**
   * 获取banner图片
   */
  getBannerList: function (storeId) {
    bannerService.getStoreBannerList('GRABADSENSE', storeId).then(res => {
      console.log(res)
      this.setData({
        banners: res
      })
    })
    // 获取banner图片
    // bannerService.getBannerList('GRABADSENSE').then(res => {
    //   console.log(res)
    //   this.setData({
    //     banners: res
    //   })
    // })
  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
      } else {
        self.setData({
          userInfo: user.wxaUser,
          hasUserInfo: true,
        })
      }
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})